<template>
  <div class="cart">
     <!-- 购物车标题 -->
     <div class="carttop">
       <span class="text">购物车({{cartLength}})</span>
     </div>
     <!-- 购物车显示区域 -->
     <scroll ref="scroll">
       <CartList></CartList>
     </scroll>
     <!-- 购物车底部区域 -->
     <div class="cartbottom">
      <div class="checkcontent">
        <CheckButton class="checkbutton" v-model="isSelectAll" @click.native="checkClick"></checkButton>
      <span>全选</span>
      </div>
      <div class="totalprice">总价：￥{{totalPrice}}</div>
      <div class="calcuate">去结算({{checkLength}})</div>
     </div>
  </div>
</template>

<script>
import CheckButton from './ChildComponents/checkButton.vue'
import CartList from './ChildComponents/cartlist.vue'
import scroll from 'components/scroll/scroll.vue'

import { mapGetters } from 'vuex'

export default {
  name: 'cart',
  methods: {
    checkClick() {
      if (this.isSelectAll) {
        // 全部选中的情况
        this.$store.state.cartList.forEach(item => (item.checked = false));
      } else {
        // 全部或者部分不选中
        this.$store.state.cartList.forEach(item => (item.checked = true));
      }
    }
  },
  components: {
    CheckButton,
    CartList,
    scroll
  },
  computed: {
    ...mapGetters(['cartLength']),
    isSelectAll() {
      if (this.$store.state.cartList.length === 0) return false
      // 使用find方法，我们这里只要找到一个没有checked的就停止，这样性能好一点
      return !this.$store.state.cartList.find(item => !item.checked)
    },
    totalPrice() {
      return this.$store.state.cartList
        .filter(item => {
          // 过滤器
          return item.checked;
        })
        .reduce((preValue, item) => {
          return preValue + item.nowPrice * item.count;
        }, 0)
        .toFixed(2);
    },
    checkLength() {
      return this.$store.state.cartList.filter(item => {
        // 过滤器
        return item.checked;
      }).length;
    },
  },
  activated() {
    this.$refs.scroll.refresh()
  }
}
</script>

<style lang="stylus" scoped>
.carttop
  display flex
  width 100%vw
  height 44px
  line-height 44px
  text-align center
  background-color #ff8198
  color #ffffff
  z-index 9
  .text
    flex 1
    font-size 20px
    font-weight 700
.wrapper
  height 434px
  overflow hidden
.cartbottom
  position: absolute
  display: flex
  bottom 50px
  height: 40px
  line-height: 40px
  width 100%
  background-color: #eee
  z-index 10
  .checkcontent
    display: flex
    align-items: center
    width: 80px
    margin-left: 10px
    .checkbutton
      width: 20px
      height: 20px
      line-height: 20px
  .totalprice
    flex 1
  .calcuate
    width: 90px
    background-color: red
    color: #ffffff
    text-align: center
</style>